package com.wjl.picture.picture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjl.picture.auth.SpaceUserAuthManager;
import com.wjl.picture.common.constant.CommonConstant;
import com.wjl.picture.common.context.UserContext;
import com.wjl.picture.common.exception.BusinessException;
import com.wjl.picture.common.exception.ErrorCode;
import com.wjl.picture.common.exception.ThrowUtils;
import com.wjl.picture.picture.dao.SpaceDao;
import com.wjl.picture.picture.model.entity.Space;
import com.wjl.picture.picture.model.enums.SpaceLevelEnum;
import com.wjl.picture.picture.model.enums.SpaceTypeEnum;
import com.wjl.picture.picture.model.request.SpaceAddRequest;
import com.wjl.picture.picture.model.request.SpaceQueryRequest;
import com.wjl.picture.picture.model.vo.SpaceVO;
import com.wjl.picture.picture.service.SpaceService;
import com.wjl.picture.user.model.entity.User;
import com.wjl.picture.user.model.enums.UserRoleEnum;
import com.wjl.picture.user.model.vo.UserVO;
import com.wjl.picture.user.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author jdd
 * @description 针对表【space(空间)】的数据库操作Service实现
 * @createDate 2024-12-20 10:02:51
 */
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceDao, Space> implements SpaceService {
    @Resource
    private UserService userService;

    @Resource
    private SpaceDao spaceDao;

    @Resource
    private TransactionTemplate transactionTemplate;


    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest) {

        // 在此处将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        // 默认值
        if (StrUtil.isBlank(spaceAddRequest.getSpaceName())) {
            space.setSpaceName("默认空间");
        }
        if (spaceAddRequest.getSpaceLevel() == null) {
            spaceAddRequest.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (spaceAddRequest.getSpaceType() == null) {
            spaceAddRequest.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        // 填充数据
        this.fillSpaceBySpaceLevel(space);
        // 数据校验
        this.validSpace(space, true);
        Long userId = UserContext.getUserId();
        space.setUserId(userId);
        // 权限校验
        if (SpaceLevelEnum.COMMON.getValue() != spaceAddRequest.getSpaceLevel() && !UserContext.isAdmin()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限创建指定级别的空间");
        }
        // 针对用户进行加锁
        String lock = String.valueOf(userId).intern();
        synchronized (lock) {
            Long newSpaceId = transactionTemplate.execute(status -> {
                if (!UserContext.isAdmin()) {
                    boolean exists = this.lambdaQuery()
                            .eq(Space::getUserId, userId)
                            .eq(Space::getSpaceType, spaceAddRequest.getSpaceType())
                            .exists();
                    ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "每个用户每类空间仅能创建一个");
                }
                // 写入数据库
                boolean result = this.save(space);
                ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
                // 返回新写入的数据 id
                return space.getId();
            });

            // 返回结果是包装类，可以做一些处理
            return Optional.ofNullable(newSpaceId).orElse(-1L);
        }
    }



    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        Integer spaceType = space.getSpaceType();
        SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(spaceType);
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        // 要创建
        if (add) {
            if (StrUtil.isBlank(spaceName)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            }
            if (spaceLevel == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不能为空");
            }
            if (spaceTypeEnum == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型不存在");
            }
        }
        // 修改数据时，如果要改空间级别
        if (spaceLevel != null && spaceLevelEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不存在");
        }
        if (spaceType != null && spaceTypeEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型不存在");
        }
        if (StrUtil.isNotBlank(spaceName) && spaceName.length() > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称过长");
        }
    }


    @Override
    public LambdaQueryWrapper<Space> getLambdaQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> spaceQueryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<Space> lambdaQueryWrapper = spaceQueryWrapper.lambda();
        if (spaceQueryRequest == null) {
            return lambdaQueryWrapper;
        }
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        // 拼接查询条件
        lambdaQueryWrapper.like(StrUtil.isNotBlank(spaceName), Space::getSpaceName, spaceName);
        lambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(spaceLevel), Space::getSpaceLevel, spaceLevel);
        lambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(id), Space::getId, id);
        lambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(userId), Space::getUserId, userId);
        lambdaQueryWrapper.eq(Space::getIsDelete, false);
        Integer spaceType = spaceQueryRequest.getSpaceType();
        lambdaQueryWrapper.eq(ObjectUtils.isNotEmpty(spaceType), Space::getSpaceType, spaceType);

        // 默认按创建时间降序排序
        if (StringUtils.isNotBlank(sortField)) {
            if ("createTime".equals(sortField)) {
                lambdaQueryWrapper.orderBy(StrUtil.isNotBlank(sortOrder), CommonConstant.SORT_ORDER_ASC.equals(sortOrder), Space::getCreateTime);
            }
            if ("updateTime".equals(sortField)) {
                lambdaQueryWrapper.orderBy(StrUtil.isNotBlank(sortOrder), CommonConstant.SORT_ORDER_ASC.equals(sortOrder), Space::getUpdateTime);
            }
        }
        return lambdaQueryWrapper;
    }


    @Override
    public SpaceVO getSpaceVO(Space space) {
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        // 1. 关联查询用户信息
        Long userId = space.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        spaceVO.setUser(userVO);
        return spaceVO;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> spacePage) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollectionUtils.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<SpaceVO> spaceVOList = spaceList.stream().map(space -> {
            SpaceVO spaceVO = SpaceVO.objToVo(space);
            Long userId = space.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userService.getUserVO(user));
            return spaceVO;
        }).collect(Collectors.toList());
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;
    }

    @Override
    public Page<SpaceVO> listSpaceVOByPage(SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long pageSize = spaceQueryRequest.getPageSize();
        Page<Space> spacePage = this.page(new Page<>(current, pageSize),
                this.getLambdaQueryWrapper(spaceQueryRequest));
        return this.getSpaceVOPage(spacePage);
    }

    @Override
    public void validDelete(List<Long> ids, User user) {
        List<Space> list = new LambdaQueryChainWrapper<>(spaceDao)
                .in(CollUtil.isNotEmpty(ids), Space::getId, ids)
                .select(Space::getId, Space::getUserId)
                .list();
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean b = list.stream().allMatch(space -> space.getUserId().equals(user.getId()));
        if (!b && !UserRoleEnum.ROLE_ADMIN.getValue().equals(user.getUserRole())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        // 根据空间级别，自动填充限额
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (spaceLevelEnum != null) {
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }
    }
    /**
     * 空间权限校验
     *
     * @param space
     */
    @Override
    public void checkSpaceAuth(Space space) {
        // 仅本人或管理员可访问
        if (!space.getUserId().equals(UserContext.getUserId()) && !UserContext.isAdmin()) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }

}




